﻿/**
 * 超链接容器，提供文件上传功能。
 */
Ext.define('Happy.form.LinkContainer', {
    extend: 'Ext.form.FieldContainer',
    alias: 'widget.happy-linkcontainer',
    requires: ['Happy.fileupload.Window'],

    /**
     * @cfg。
     */
    uploadButtonText: '上传',
    /**
     * @cfg。
     */
    viewButtonText: '查看',
    /**
     * @cfg {Object} fileUploadFormConfig。
     */
    /**
     * @cfg {Object} textFieldConfig。
     */

    /**
     * 重写 ExtJs。
     * 
     * @protected
     */
    initComponent: function () {
        var me = this;

        me.configItems();

        me.callParent(arguments);
    },

    /**
     * @protected
     */
    configItems: function () {
        var me = this;

        Ext.apply(me, {
            layout: 'hbox',
            items: [
                Ext.applyIf({
                    xtype: 'textfield',
                    flex: 1,
                    name: me.name
                }, me.textFieldConfig || {}),
                {
                    xtype: 'button',
                    text: me.viewButtonText,
                    margin: '0 0 0 5',
                    handler: Ext.bind(me.on_Happy_form_LinkContainer_ViewButton_Click_Handler, me)
                },
                {
                    xtype: 'button',
                    text: me.uploadButtonText,
                    margin: '0 5',
                    handler: Ext.bind(me.on_Happy_form_LinkContainer_UploadButton_Click_Handler, me)
                }
            ]
        });
    },

    /**
     * @private
     */
    on_Happy_form_LinkContainer_ViewButton_Click_Handler: function () {
        var me = this;

        var url = me.down('textfield').getValue();
        if (!url) {
            return;
        }

        me.showLink(url);
    },

    /**
     * @protected
     *
     * @param {String} url
     */
    showLink: function (url) {
        var me = this;

        window.open(url, 'blank');
    },

    /**
     * @private
     */
    on_Happy_form_LinkContainer_UploadButton_Click_Handler: function () {
        var me = this;

        var window = Ext.create('Happy.fileupload.Window', {
            fileUploadFormConfig: me.fileUploadFormConfig
        }).show();
        window.on('fileuploaded', me.on_Happy_form_LinkContainer_FileupLoaded_Handler, me);
    },

    /**
     * @private
     */
    on_Happy_form_LinkContainer_FileupLoaded_Handler: function (_, result) {
        var me = this;

        me.down('textfield').setValue(result.url);
    }
});